package com.xinruke.hostels.systemmanage.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.central.manage.interfaces.dto.*;
import com.xinruke.hostels.common.cache.ManageUserCache;
import com.xinruke.hostels.common.cache.vo.LoginManageResultVO;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.YewuyonghuCaozuoRizhi;
import com.xinruke.hostels.common.po.YwFangjian;
import com.xinruke.hostels.common.po.YwLouceng;
import com.xinruke.hostels.common.po.YwLoudong;
import com.xinruke.hostels.common.service.OperateLogService;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.system.manage.interfaces.dto.FloorsCountQueryDTO;
import com.xinruke.hostels.system.manage.interfaces.dto.RoomCountQueryDTO;
import com.xinruke.hostels.systemmanage.mapper.YwFangjianMapper;
import com.xinruke.hostels.systemmanage.mapper.YwLoucengMapper;
import com.xinruke.hostels.systemmanage.mapper.YwLoudongMapper;
import com.xinruke.hostels.systemmanage.service.BuildingService;
import com.xinruke.hostels.systemmanage.service.FloorService;
import com.xinruke.hostels.systemmanage.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 楼栋管理
 *
 * @author Jinz
 * @date 2019-06-26 23:43
 */
@Service
@Slf4j
public class BuildingServiceImpl implements BuildingService {

    @Autowired
    private RoomService roomService;

    @Autowired
    private FloorService floorService;

    @Autowired
    private YwLoucengMapper loucengMapper;

    @Autowired
    private YwFangjianMapper fangjianMapper;

    @Autowired
    private YwLoudongMapper ywLoudongMapper;

    @Autowired
    private ManageUserCache manageUserCache;

    @Autowired
    OperateLogService operateLogService;

    @Override
    public ResultVO add(BuildingAddQueryDTO buildingAddQueryDTO) {
        ResultVO resultVO;
        YwLoudong ywLoudong = new YwLoudong();
        BeanUtils.copyProperties(buildingAddQueryDTO, ywLoudong);

        LoginManageResultVO userInfo = manageUserCache.getLoginManageUserInfo();
        ywLoudong.setJiudianId(userInfo.getJiudianId());
        ywLoudong.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
        ywLoudong.setChuangjianrenId(userInfo.getId());
        ywLoudong.setChuangjianshijian(new Date());
        try {
            int check = ywLoudongMapper.insert(ywLoudong);
            if (check > 0) {
                resultVO = ResultVO.success();
            } else {
                resultVO = ResultVO.fail();
            }
        } catch (Exception e) {
            resultVO = ResultVO.fail();
            log.error("楼栋新增异常，楼栋信息为={}", JSONObject.toJSON(ywLoudong), e);
        }
        return resultVO;
    }

    @Override
    public ResultVO modify(BuildingUpdateQueryDTO buildingUpdateQueryDTO) {
        ResultVO resultVO = null;
        YwLoudong ywLoudong = new YwLoudong();
        BeanUtils.copyProperties(buildingUpdateQueryDTO, ywLoudong);
        ywLoudong.setGengxinshijian(new Date());
        ywLoudong.setGengxinrenId(manageUserCache.getCurrentUserId());
        try {
            int check = ywLoudongMapper.updateByPrimaryKeySelective(ywLoudong);
            if (check > 0) {
                resultVO = ResultVO.success();
            } else {
                resultVO = ResultVO.fail();
            }
        } catch (Exception e) {
            resultVO = ResultVO.fail();
            log.error("楼栋修改异常，楼栋信息为={}", JSONObject.toJSON(ywLoudong), e);
        }
        return resultVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVO delete(BuildingDelQueryDTO buildingDelQueryDTO) {
        ResultVO resultVO = ResultVO.fail();

        int loudongId = buildingDelQueryDTO.getId();

        //删除楼栋
        YwLoudong ywLoudong = new YwLoudong();
        ywLoudong.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        ywLoudong.setGengxinshijian(new Date());
        ywLoudong.setGengxinrenId(manageUserCache.getCurrentUserId());

        QueryConditions loudongQueryCondition = new QueryConditions();
        loudongQueryCondition.addCondition("id", EConditionOperator.EQULS, loudongId);
        loudongQueryCondition.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        MyExample loudongMyExample = new MyExample(YwLoudong.class, loudongQueryCondition);
        int loudongRet = ywLoudongMapper.updateByExampleSelective(ywLoudong, loudongMyExample);
        if (loudongRet <= 0) {
            log.error("删除楼栋失败，楼栋id[" + loudongId + "]");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            resultVO.setMessage("删除楼栋失败");
            return resultVO;
        }

        //删除所有的楼层
        YwLouceng louceng = new YwLouceng();
        louceng.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        louceng.setGengxinrenId(manageUserCache.getCurrentUserId());
        louceng.setGengxinshijian(new Date());

        QueryConditions loucengQueryCondition = new QueryConditions();
        loucengQueryCondition.addCondition("loudongId", EConditionOperator.EQULS, loudongId);
        loucengQueryCondition.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        MyExample loucengMyExample = new MyExample(YwLouceng.class, loucengQueryCondition);
        loucengMapper.updateByExampleSelective(louceng, loucengMyExample);

        //删除所有的房间
        YwFangjian fangjian = new YwFangjian();
        fangjian.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        fangjian.setGengxinrenId(manageUserCache.getCurrentUserId());
        fangjian.setGengxinshijian(new Date());

        QueryConditions fangjianQueryCondition = new QueryConditions();
        fangjianQueryCondition.addCondition("loudongId", EConditionOperator.EQULS, loudongId);
        fangjianQueryCondition.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        MyExample fangjianMyExample = new MyExample(YwFangjian.class, fangjianQueryCondition);
        fangjianMapper.updateByExampleSelective(fangjian, fangjianMyExample);

        //写入操作日志
        YewuyonghuCaozuoRizhi yewuyonghuCaozuoRizhi = new YewuyonghuCaozuoRizhi("楼栋", "删除楼栋", "楼栋id[" + loudongId + "]");
        operateLogService.writeOperateLog(yewuyonghuCaozuoRizhi);

        resultVO = ResultVO.success();

        return resultVO;
    }

    @Override
    public ResultVO<BuildingDetailQueryResultDTO> detail(BuildingDetailQueryDTO params) {
        ResultVO<BuildingDetailQueryResultDTO> resultVO = ResultVO.success();
        YwLoudong param = new YwLoudong();
        param.setId(params.getId());
        YwLoudong ywLoudong = ywLoudongMapper.selectByPrimaryKey(param);
        BuildingDetailQueryResultDTO buildingDetailQueryResultDTO = new BuildingDetailQueryResultDTO();
        BeanUtils.copyProperties(ywLoudong, buildingDetailQueryResultDTO);

        RoomCountQueryDTO roomCountQueryDTO = new RoomCountQueryDTO();
        roomCountQueryDTO.setLoudongId(params.getId());
        roomCountQueryDTO.setJiudianId(manageUserCache.getJiudianId());

        FloorsCountQueryDTO floorsCountQueryDTO = new FloorsCountQueryDTO();
        floorsCountQueryDTO.setLoudongId(param.getId());
        buildingDetailQueryResultDTO.setLoucengshu(floorService.count(floorsCountQueryDTO));
        buildingDetailQueryResultDTO.setFangjianshu(roomService.count(roomCountQueryDTO));
        resultVO.setData(buildingDetailQueryResultDTO);
        return resultVO;
    }

    @Override
    public ResultVO<RowsDataVO<BuildingDetailQueryResultDTO>> buildings(BuildingsQueryDTO pamras) {
        RowsDataVO<BuildingDetailQueryResultDTO> dataVO = new RowsDataVO<>();
        QueryConditions conditions = new QueryConditions();
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());

        MyExample example = new MyExample(YwLoudong.class, conditions, pamras.getOrderFields());
        Page<BuildingDetailQueryResultDTO> page = PageHelper.startPage(pamras.getPageNo(), pamras.getPageSize());
        List<YwLoudong> ywLoudongs = ywLoudongMapper.selectByExample(example);

        List<BuildingDetailQueryResultDTO> resultList = ywLoudongs.stream().map(n -> {
            BuildingDetailQueryResultDTO louDong = new BuildingDetailQueryResultDTO();
            BeanUtils.copyProperties(n, louDong);
            return louDong;
        }).collect(Collectors.toList());
        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(resultList);
        ResultVO<RowsDataVO<BuildingDetailQueryResultDTO>> result = ResultVO.success();
        result.setData(dataVO);
        return result;
    }
}
